package org.swift.mashup.wsdl;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;

import javax.xml.stream.XMLStreamException;

import org.apache.axis2.AxisFault;
import org.apache.commons.io.IOUtils;
import org.swift.commons.client.Call;
import org.swift.commons.client.RestCall;

/**
 * Might not even need this class (at least if we are using SoapUI, because it
 * takes a URL and does this type of work for us)
 * 
 * @author dhesson
 */
public class UrlContentProvider implements ContentProvider<String> {

	private boolean caching = true;

	private String content = null;

	private URL url = null;

	public UrlContentProvider(URL url) {
		setURL(url);
	}

	public UrlContentProvider(URL url, boolean useCaching) {
		this(url);
		setCaching(useCaching);
	}

	public String getContent() {
		if (content != null && caching)
			return content;
		try {
			return (content = fetchContent(this.getURL()));
		
		} catch (XMLStreamException e) {
			throw new RuntimeException(e);
		} catch (AxisFault e) {
			throw new RuntimeException(e);
		}
	}

	protected String fetchContent(URL url) throws XMLStreamException, AxisFault {
		Call call;
		try {
			call = new RestCall(url.toExternalForm(), "GET");
		} catch (MalformedURLException e) {
			throw new RuntimeException(e);
		}
		InputStream is = call.sendRecieve(Collections.<String,Object>emptyMap());
		try {
			return new String(IOUtils.toByteArray(is));
		} catch (IOException e) {
			throw AxisFault.makeFault(e);
		}
		
	}

	protected URL getURL() {
		return url;
	}

	protected void setURL(URL url) {
		this.url = url;
	}

	protected boolean isCaching() {
		return caching;
	}

	protected void setCaching(boolean caching) {
		this.caching = caching;
	}
}
